<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { CircleCloseFilled, UploadFilled } from '@element-plus/icons-vue'
import { ElMessage, genFileId } from 'element-plus'
import { upload_file_action } from '@/api/file'
import useTokenStore from '@/stores/token'
import { CODE } from '@/api/constants'

const emit = defineEmits(['on-upload-success']);

const upload = ref()
const isSubmitting = ref(false) // 上传状态标识

const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

const validateFile = (file) => {
  const isPDF = file.type === 'application/pdf'
  const isLt20M = file.size / 1024 / 1024 <= 20

  if (!isPDF) {
    ElMessage.error('只能上传PDF格式的文件!')
    isSubmitting.value = false
    return false
  }
  if (!isLt20M) {
    ElMessage.error('文件大小不能超过20MB!')
    isSubmitting.value = false
    return false
  }
  return true
}

const submit = () => {
  isSubmitting.value = true
  upload.value.submit()
}

const abort = () => {
  upload.value.abort()
  isSubmitting.value = false
}

defineExpose({ submit, abort, isSubmitting })

/*
 * 一系列中断文件上传事件监听
 */
onMounted(() => {
    // page 刷新/关闭 监听
    window.addEventListener('beforeunload', handleUnload)
})

onBeforeUnmount(() => {
  window.removeEventListener('beforeunload', handleUnload)
  if (isSubmitting.value) {
    abort()
    ElMessage.error("文件上传取消！")
  }
})

const handleUnload = async (e) => {
  if (!isSubmitting.value) return
  e.preventDefault()
  e.returnValue = '文件正在上传，确定要离开吗？'
}

const onSuccess = (resp) => {
    isSubmitting.value = false
    if (resp.code != CODE.OK) {
        ElMessage.error(resp.msg)
    } else {
        emit('on-upload-success')
        ElMessage.success("上传成功")
    }
}

const file_list = ref([])
const hasFile = computed(()=>{
  return file_list.value.length > 0 && file_list.value.some(file => file.status === "ready")
})
</script>

<template>
  <div class="upload-container">
    <el-upload
        ref="upload"
        drag
        :action="upload_file_action"
        :headers="useTokenStore().getAuthHeader()"
        :limit="1"
        :auto-upload="false"
        :before-upload="validateFile"
        :on-exceed="handleExceed"
        :on-success="onSuccess"
        :on-error="() => isSubmitting = false"
        v-model:file-list="file_list"
    >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
        Drop file here or <em>click to upload</em>
        </div>
        <template #tip>
        <div class="el-upload__tip">
            pdf file with a size less than 20M
        </div>
        </template>
    </el-upload>

    <div class="action-buttons">
      <el-button 
        :type="isSubmitting ? 'danger' : 'primary'"
        :icon="isSubmitting ? CircleCloseFilled : UploadFilled"
        @click="isSubmitting ? abort() : submit()"
        :disabled="!hasFile"
      >
        {{ isSubmitting ? '取消上传' : '提交文件' }}
      </el-button>
    </div>
  </div>
</template>


<style scoped>
.upload-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.action-buttons {
  display: flex;
  justify-content: center;
}
</style>